import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/user/entities/user.entity';
import { Repository } from 'typeorm';
import { Public } from 'src/customDecorator';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.userService.findOne(username);
    if (user && user.password === pass) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  // @Public()
  async signIn(username: string, pass: string): Promise<any> {
    const user = await this.userRepository.createQueryBuilder()
      .select()
      .where('user.username = :username', { username })
      .getOne()

    if (user?.password !== pass) {
      throw new UnauthorizedException();
    }
    const payload = { sub: user.id, username: user.username };
    // TODO: 生成一个 JWT，并在这里返回
    // 而不是返回一个用户对象
    return {
      access_token: await this.jwtService.signAsync(payload),
    }
  }

  async signUp(username: string, pass: string): Promise<any> {

  }

  async signOut(username: string): Promise<any> {

  }
}
